package com.north.light.libltobserver.utils;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * FileName: LTClassType
 * Author: lzt
 * Date: 2022/11/16 17:16
 */
public class LTClassType implements Serializable {

    public static <T> Class getInstance(Object src) {
        return getInstance(src, 0);
    }

    /**
     * 获取对象的泛型
     *
     * @param src   待获取泛型对象
     * @param index 泛型的位置
     * @param <T>   泛型
     * @return 泛型Class类
     */
    public static <T> Class getInstance(Object src, int index) {
        if (src == null || index < 0) {
            return null;
        }
        Class<?> aClass = src.getClass();
        Type gSuperclass = aClass.getGenericSuperclass();
        if (gSuperclass instanceof ParameterizedType) {
            try {
                ParameterizedType pType = (ParameterizedType) gSuperclass;
                Type[] types = pType.getActualTypeArguments();
                if (index < types.length) {
                    Class<?> desClass = (Class<T>) types[index];
                    return desClass;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
